package com._520it.crm.service.impl;

import com._520it.crm.domain.*;
import com._520it.crm.mapper.*;
import com._520it.crm.page.PageResult;
import com._520it.crm.query.OrderBillQueryObject;
import com._520it.crm.service.IOrderBillService;
import com._520it.crm.util.DateUtil;
import com._520it.crm.util.Premium;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrderBillServiceImpl implements IOrderBillService {
    @Autowired
    private OrderBillMapper orderBillMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private ClientCarMapper clientCarMapper;
    @Autowired
    private InsuranceMapper insuranceMapper;
    @Autowired
    private TaxMapper taxMapper;
    @Override
    public int insert(OrderBill record) {
        return orderBillMapper.insert(record);
    }

    @Override
    public OrderBill selectByPrimaryKey(Long id) {
        return orderBillMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<OrderBill> selectAll() {
        return orderBillMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(OrderBill record) {
        return orderBillMapper.updateByPrimaryKey(record);
    }

    @Override
    public PageResult queryDataList(OrderBillQueryObject qo) {
        //根据条件查询总记录数
        Long count = orderBillMapper.queryForCount(qo);
        if (count <= 0){
            return new PageResult(0L, Collections.EMPTY_LIST);
        }
        List<Map> data = orderBillMapper.queryDataList(qo);
        return new PageResult(count,data);
    }

    @Override
    public OrderBill saveData1(OrderBill ob) {
        ob.setInsureBillNumber(DateUtil.date());
        Product p = productMapper.selectByPrimaryKey(ob.getProduct().getId());
        ob.setProduct(p);
        Insurance insurance = insuranceMapper.selectByPrimaryKey(p.getInsuranceId());
        ob.setInsurance(insurance);
        ob.setInputTime(new Date());
        ob.setEmployee((Employee) SecurityUtils.getSubject().getPrincipal());
        Tax tax = taxMapper.selectByPrimaryKey(p.getTaxId());
        ob.setRatePayment(tax);
        ob.setRemove(OrderBill.STATUS_NO);
        ob.setStatus(OrderBill.UNSUBMIT);
        orderBillMapper.saveData1(ob);
        return ob;
    }

    @Override
    public PageResult selectBill(OrderBillQueryObject qo) {
        if(StringUtils.isNotBlank(qo.getProductName())){
            Product product = productMapper.selectByPrimaryKey(Long.parseLong(qo.getProductName()));
            qo.setProductName(product.getName());
        }
        if(StringUtils.isNotBlank(qo.getOrganizationNameD())){
            Organization organization = organizationMapper.selectByPrimaryKey(Long.parseLong(qo.getOrganizationNameD()));
            qo.setOrganizationNameD(organization.getOrganizationName());
        }
        Long total = orderBillMapper.selectForCount(qo);
        if (total <= 0){
            return new PageResult(0L, Collections.EMPTY_LIST);
        }
        List<Map> data = orderBillMapper.selectForList(qo);
        return new PageResult(total,data);
    }

    @Override
    public void insertData(OrderBill ob, boolean isequalRec, boolean equalOwnerId) {
        Client aplicant = new Client();
        Client recognizee = new Client();
        Client carOwner = new Client();
        aplicant =  clientMapper.queryByidcardnumber(ob.getAplicant().getIdcardnumber());
        recognizee = clientMapper.queryByidcardnumber(ob.getRecognizee().getIdcardnumber());
        carOwner = clientMapper.queryByidcardnumber(ob.getCarOwner().getIdcardnumber());
        if(aplicant.getId() == null){
            aplicant.setInputtime(new Date());
            aplicant.setUsername(aplicant.getRealname());
            aplicant.setPassword("12345678");
            aplicant.setInputor((Employee) SecurityUtils.getSubject().getPrincipal());
            aplicant.setApplicant(0);
            aplicant.setClientsn(11L);
            clientMapper.insert(aplicant);
        }

        if(isequalRec == true){
            recognizee = aplicant;
            recognizee.setId(null);
            recognizee.setApplicant(-1);
        }else{
            recognizee.setInputtime(new Date());
            recognizee.setUsername(recognizee.getRealname());
            recognizee.setPassword("12345678");
            recognizee.setInputor((Employee) SecurityUtils.getSubject().getPrincipal());
            recognizee.setApplicant(-1);
            recognizee.setClientsn(12L);

        }

        if(equalOwnerId == true){
            carOwner = aplicant;
            carOwner.setId(null);
            carOwner.setApplicant(-1);
        }else{
            carOwner.setInputtime(new Date());
            carOwner.setUsername(carOwner.getRealname());
            carOwner.setPassword("12345678");
            carOwner.setInputor((Employee) SecurityUtils.getSubject().getPrincipal());
            carOwner.setApplicant(1);
            carOwner.setClientsn(13L);

        }
        if(recognizee.getId() != null){
            clientMapper.insert(recognizee);
        }

        if(carOwner.getId() != null){
            clientMapper.insert(carOwner);
        }
        clientCarMapper.insert(ob.getClientCar());
        ob.setAplicant(aplicant);
        ob.setRecognizee(recognizee);
        ob.setCarOwner(carOwner);
        ob.setRemove(0);
        ob.setStatus(0);
        orderBillMapper.updateData(ob);
    }

    @Override
    public Premium selectPremiumByBillId(Long id) {
        Premium premium = new Premium();
        OrderBill bill = orderBillMapper.selectPremiumByBillId(id);
        Insurance insurance = insuranceMapper.selectByPrimaryKey(bill.getProduct().getInsuranceId());
        Tax tax = taxMapper.selectByPrimaryKey(bill.getProduct().getTaxId());
        if (bill != null) {
            premium.setInsureName(insurance.getInsureRisk());
            premium.setProductName(bill.getProduct().getName());
            premium.setInsurancePrice(insurance.getInsurancePrice());
            BigDecimal add = tax.getPayable().add(tax.getBackCost().add(tax.getOverdueFine()));
            premium.setRatePayment(add);
            premium.setPremium(bill.getProduct().getPrice());
            BigDecimal sum = premium.getPremium().add(premium.getRatePayment());
            premium.setPremiumSu(sum);
            return premium;
        }
        return premium;
    }

    @Override
    public void updateById(Long id) {
        orderBillMapper.updateById(id,OrderBill.PREUNDERWRITING);
    }

    @Override
    public int updateStatusById(long orderBillId, int status) {
        OrderBill orderBill = new OrderBill();
        orderBill.setId(orderBillId);
        orderBill.setWittingDate(new Date());
        switch (status) {
            case 6:
                orderBill.setStatus(OrderBill.EXPIRED);
                break;
            case 4:
                orderBill.setStatus(OrderBill.PREPAYMENT);
                break;
            case 3:
                orderBill.setStatus(OrderBill.PREREVISE);
                break;
        }
        return orderBillMapper.updateStatusById(orderBill);
    }

    @Override
    public void updateStatusByPay(OrderBill orderBill) {
        orderBillMapper.updateStatusByPay(orderBill);
    }

    @Override
    public void issueSendBackUpdate(Long orderBillId) {
        orderBillMapper.issueSendBackUpdate(orderBillId);
    }

    @Override
    public OrderBill selectById(Long id) {
        return orderBillMapper.selectById(id);
    }

    @Override
    public void removeById(Long orderBillId,int remove, int status) {
        orderBillMapper.removeById(orderBillId,remove,status);
    }

    @Override
    public void updateOrderBill(OrderBill ob) {
        orderBillMapper.updateOrderBill(ob);
    }

    @Override
    public void updateTime(OrderBill ob) {
        orderBillMapper.updateTime(ob);
    }
}
